/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Client.Online;

import Client.AboutBox;
import Client.AePlayWave;
import Client.Client;
import Client.ClientUtils;
import GroupChat.ConfirmGroupChatRequest;
import GroupChat.ContactSelectionDialog;
import GroupChat.GroupConversasion;
import java.awt.AWTException;
import java.awt.Color;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.TrayIcon.MessageType;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JFileChooser;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.ListModel;

/**
 *
 * @author TienNT
 */
public class Client_Dashboard extends javax.swing.JFrame {

    private Client mClient;
    private ArrayList<ContactEntry> mContactEntries;
    public HashMap<String, PrivateConversasion> mPrivateConversasionList;
    private HashMap<Integer, GroupConversasion> mGroupConversasionList;
    private ArrayList<String> mIgnoredUser;
//    private boolean mIgnoredUserChanged;
    private String tempPath;
    private TrayIcon trayIcon;
    private SystemTray systemTray;

    /**
     * Creates new form Server
     */
    public Client_Dashboard(Client client, String status) {
        mIgnoredUser = new ArrayList<>();
        mContactEntries = new ArrayList<>();
        mClient = client;
        mPrivateConversasionList = new HashMap<>();
        mGroupConversasionList = new HashMap<>();
        System.out.println("I'm " + mClient.getClientName());
        initComponents();
        txtStatusText.setText(status);
//        mIgnoredUserChanged = false;
        try {
            Image e = ImageIO.read(getClass().getResource("/tray_icon.png"));
            trayIcon = new TrayIcon(e);
            trayIcon.setImageAutoSize(true);
            trayIcon.setToolTip("Java LAN chatting");
            PopupMenu popup = new PopupMenu();
            MenuItem popup_about=new MenuItem("About");
            MenuItem popup_exit=new MenuItem("Exit");
            popup.add(popup_about);
            popup.addSeparator();
            popup.add(popup_exit);
            trayIcon.setPopupMenu(popup);
            popup_about.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    AboutBox about=new AboutBox(Client_Dashboard.this, true);
                    about.setVisible(true);
                }
            });
            popup_exit.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    menuLogoutActionPerformed(e);
                }
            });
            systemTray = SystemTray.getSystemTray();
            systemTray.add(trayIcon);
//            trayIcon.displayMessage("foo", "bar", MessageType.INFO);
            

        } catch (IOException | AWTException ex) {
            Logger.getLogger(Client_Dashboard.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public ArrayList<String> getIgnoredUser() {
        return this.mIgnoredUser;
    }

    public ArrayList<ContactEntry> getContactList() {
        return this.mContactEntries;
    }

    public void sendMessageToServer(String message) {
        mClient.sendMessageToServer(message);
    }

    public String getClientName() {
        return mClient.getClientName();
    }

    public void run() {
        // TODO Auto-generated method stub
        while (true) {
            String s = mClient.receiveMessage();
            if (s != null) {
                try {
                    String command = s.substring(0, 2);
                    switch (command) {
                        case ClientUtils.CONTACT_LIST_CHANGED:
                            updateContactList(s);
                            break;
                        case ClientUtils.ASK_FILE_TRANSFER_OK:
                            processAskFileTransferOk(s);
                            break;
                        case ClientUtils.CONFIRM_FILE_TRANSFER_TOCLIENT:
                            processConfirmFileTransfer(s);
                            break;
                        case ClientUtils.NEW_PRIVATE_MESSAGE_COMMING:
                            receivePrivateMessage(s);
                            break;
                        case ClientUtils.SEND_CONTACT_LIST_COMMING:
                            receiveContactList();
                            break;
                        case ClientUtils.REQUEST_GROUP_CHAT_COMMING:
                            processRequestGroupChatComming(s);
                            break;
                        case ClientUtils.CONTACT_JOINED_GROUP:
                            processContactJoinedGroup(s);
                            break;
                        case ClientUtils.CONTACT_NOT_JOINED_GROUP:
                            processContactDelineGroup(s);
                            break;
                        case ClientUtils.REQUEST_FORCE_LOGOUT:
                            forcedLogOut();
                            break;
                        case ClientUtils.IGNORE_LIST:
                            receiveIgnoreList();
                            break;
                        case ClientUtils.BUZZ_INCOMING:
                            buzzReceived();
                            break;
                        case ClientUtils.GROUP_ID_COMMING:
                            processGroupIdComming(s);
                            break;
                        case ClientUtils.NEW_GROUP_MESSAGE_COMMING:
                            processNewGroupMessageComming(s);
                            break;
                        case ClientUtils.FROM_SERVER_KICKOUT_GROUP:
                            processKickOutGroup(s);
                            break;
                        case ClientUtils.CONTACT_LEAVE_GROUP:
                            processContactLeaveGroup(s);
                            break;
                        case ClientUtils.FILE_TRANSFERING_TOCLIENT:
                            processFileTransferToClient(s);
                            break;
                        default:
                            break;
                    }
                } catch (Exception ex) {
                    System.err.println(ex.getMessage());
                }
            }

        }
    }

    private void receiveIgnoreList() {
        mIgnoredUser = new ArrayList<>();
        String s = mClient.receiveMessage();
        if (s.length() == 0) {
            return;
        }
        System.out.println("ign" + s);
        String[] strings = s.split(":");
        mIgnoredUser = new ArrayList<>();
        mIgnoredUser.addAll(Arrays.asList(strings));
    }

    private void processContactJoinedGroup(String s) {
        /**
         * Command structure: ClientUtils.CONTACT_JOINED_GROUP + ":" +
         * clientName + ":" + mGroupID
         */
        String[] strings = s.split(":");
        int id = Integer.parseInt(strings[2]);
        mGroupConversasionList.get(id).updateConversasion("notify", strings[1] + " has accept to join this group!");

    }

    private void processKickOutGroup(String s) {
        // Xay ra khi client minh dong cua so group chat
        /**
         * Command structure: ClientUtils.CFROM_SERVER_KICKOUT_GROUP + ":" +
         * mGroupID
         */
        String[] strings = s.split(":");
        int id = Integer.parseInt(strings[1]);
        mGroupConversasionList.get(id).dispose();
        mGroupConversasionList.remove(id);
    }

    private void processContactDelineGroup(String s) {
        /**
         * Command structure: ClientUtils.CONTACT_DECLINE_GROUP + ":" +
         * clientName + ":" + mGroupID
         */
        String[] strings = s.split(":");
        int id = Integer.parseInt(strings[2]);
        mGroupConversasionList.get(id).updateConversasion("notify", strings[1] + " has decline to join this group!");

    }

    private void processContactLeaveGroup(String s) {
        String[] strings = s.split(":");
        int id = Integer.parseInt(strings[2]);
        mGroupConversasionList.get(id).updateConversasion("notify", strings[1] + " has left this group!");
    }

    /* private void processContactLeavePrivate(String s){
     String name=s.substring(2);
     mPrivateConversasionList.get(name).updateConversasion("notify", name + " has loged out!");
     }*/
    private void buzzReceived() {
        String srcClient = mClient.receiveMessage();
        if (mIgnoredUser.contains(srcClient)) {
            return;
        }
        PrivateConversasion conversasion;
        new AePlayWave("images/buzz.wav").start();
        if (mPrivateConversasionList.containsKey(srcClient)) {
            conversasion = mPrivateConversasionList.get(srcClient);
            if (!conversasion.isVisible()) {
                conversasion.setVisible(true);
            }
            conversasion.requestFocus();

        } else {
            conversasion = new PrivateConversasion(mClient, srcClient, true, true);
            mPrivateConversasionList.put(srcClient, conversasion);

            conversasion.setVisible(true);
            conversasion.requestFocus();
        }
        try {
            conversasion.updateConversasion("buzz", "BUZZ!");
            conversasion.buzzExe();
        } catch (InterruptedException ex) {
        }
    }

    public void forcedLogOut() {
        if (!mGroupConversasionList.isEmpty()) {
            Set<Integer> iGroupIdList = mGroupConversasionList.keySet();
            for (int i : iGroupIdList) {
                mClient.sendMessageToServer(ClientUtils.REQUEST_OUT_GROUP + ":" + i);
            }
        }
        mClient.closeSession();
        System.exit(0);
    }

    public void receivePrivateMessage(String s) {

        String[] s2 = s.split(":");
        String srcClient = s2[1];
        if (mIgnoredUser.contains(srcClient)) {
            return;
        }
        String message = s2[3];

        trayIcon.displayMessage(srcClient, message, MessageType.NONE);

        if (mPrivateConversasionList.containsKey(srcClient)) {
            PrivateConversasion conversasion = mPrivateConversasionList.get(srcClient);
            if (!conversasion.isVisible()) {
                conversasion.setVisible(true);
            }
            conversasion.requestFocus();
            conversasion.updateConversasion(srcClient, message);
        } else {
            PrivateConversasion conversasion = new PrivateConversasion(mClient, srcClient, true, true);
            mPrivateConversasionList.put(srcClient, conversasion);
            conversasion.updateConversasion(srcClient, message);
            conversasion.setVisible(true);
            conversasion.requestFocus();
        }
    }

    private void processRequestGroupChatComming(String s) {
        // Mot loi moi chat nhom duoc gui toi
        ConfirmGroupChatRequest confirmDialog = new ConfirmGroupChatRequest(mClient, s);
        int decide = confirmDialog.showDialog();
        if (decide == 1) {
            GroupConversasion groupConversasion = new GroupConversasion(mClient, confirmDialog.getGroupId());
            groupConversasion.setVisible(true);
            mGroupConversasionList.put(confirmDialog.getGroupId(), groupConversasion);
        }
    }

    private void processGroupIdComming(String s) {
        // Khi client nay gui yeu cau chat nhom di, server se tra lai group id cho
        // client nay de client tao GroupConversasion

        int groupId = Integer.parseInt(s.substring(3));
        GroupConversasion groupConversasion = new GroupConversasion(mClient, groupId);
        groupConversasion.setVisible(true);
        mGroupConversasionList.put(groupId, groupConversasion);
    }

    private void processNewGroupMessageComming(String s) {
        /**
         * Message structure: ServerUtils.NEW_GROUP_MESSAGE + ":" + id + ":" +
         * from + ":" + message;
         */
        String[] strings = s.split(":");
        int id = Integer.parseInt(strings[1]);
        mGroupConversasionList.get(id).updateConversasion(strings[2], strings[3]);
    }

    public void retrieveContactEntries() {
        int size = Integer.parseInt(mClient.receiveMessage());
        URL urlToContactIcon = this.getClass().getResource("/icon.png");
        for (int i = 0; i < size; i++) {
            String receive = mClient.receiveMessage();
            /**
             * Command structure:
             * username:statustext:status(online/offline=boolean);
             */
            String[] data = receive.split(":");
            String username = data[0], statustext = data[1], sstatus = data[2];
            boolean status = Boolean.parseBoolean(sstatus);
            if (!username.equalsIgnoreCase(mClient.getClientName())) {
                mContactEntries.add(new ContactEntry(username, urlToContactIcon,
                        statustext, status));
            }
        }

    }

    public void receiveContactList() {
        retrieveContactEntries();
        listContacts.setListData(mContactEntries.toArray());
        listContacts.setCellRenderer(new ContactCellRenderer());
        jScrollPane1.setViewportView(listContacts);
    }

    public void updateContactList(String s) {
        String[] temps = s.split(":");
        if (temps[1].equals(ClientUtils.CODE_LOGIN) && !temps[2].equals(mClient.getClientName())) {
            for (int i = 0; i < mContactEntries.size(); i++) {
                if (mContactEntries.get(i).getContactName().equals(temps[2])) {
                    mContactEntries.get(i).setOnlineStatus(true);
                    if (mPrivateConversasionList.containsKey(temps[2])) {
                        mPrivateConversasionList.get(temps[2]).setPeerOnline();
                    }
                }
            }
        } else if (temps[1].equals(ClientUtils.CODE_LOGOUT)) {
            for (int i = 0; i < mContactEntries.size(); i++) {
                if (mContactEntries.get(i).getContactName().equals(temps[2])) {
                    mContactEntries.get(i).setOnlineStatus(false);
                    if (mPrivateConversasionList.containsKey(temps[2])) {
                        mPrivateConversasionList.get(temps[2]).setPeerOffline();
                    }
                }
            }
        } else if (temps[1].equals(ClientUtils.CODE_REGISTER)) {
            URL urlToContactIcon = this.getClass().getResource("/icon.png");
            mContactEntries.add(new ContactEntry(temps[2], urlToContactIcon, temps[3], Boolean.valueOf(temps[4])));
        } else if (temps[1].equals(ClientUtils.CODE_STATUS_CHANGE)) {
            for (int i = 0; i < mContactEntries.size(); i++) {
                if (temps[2].equals(mContactEntries.get(i).getContactName())) {
                    mContactEntries.get(i).setStatus(temps[3]);
                }
            }
        }

        listContacts.setListData(mContactEntries.toArray());
        listContacts.setCellRenderer(new ContactCellRenderer());
        jScrollPane1.setViewportView(listContacts);

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed"
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jRadioButtonMenuItem1 = new javax.swing.JRadioButtonMenuItem();
        jMenuItem1 = new javax.swing.JMenuItem();
        jScrollPane1 = new javax.swing.JScrollPane();
        listContacts = new javax.swing.JList();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        txtStatusText = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        menuMagaeIgnored = new javax.swing.JMenuItem();
        menuLogout = new javax.swing.JMenuItem();
        menuExit = new javax.swing.JMenuItem();
        jMenu3 = new javax.swing.JMenu();
        menuGroupChat = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        menuAbout = new javax.swing.JMenuItem();

        jRadioButtonMenuItem1.setSelected(true);
        jRadioButtonMenuItem1.setText("jRadioButtonMenuItem1");

        jMenuItem1.setText("jMenuItem1");

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("LAN Chat Messenger");
        setResizable(false);
        addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                formMousePressed(evt);
            }
        });
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        listContacts.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                listContactsMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(listContacts);

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/myicon.png"))); // NOI18N
        jLabel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(255, 204, 0)));
        jLabel1.setOpaque(true);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(5, 5, 5)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(5, 5, 5))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGap(5, 5, 5)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(5, 5, 5))
        );

        txtStatusText.setEditable(false);
        txtStatusText.setText("What's on your mind?");
        txtStatusText.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                txtStatusTextMouseClicked(evt);
            }
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                txtStatusTextMouseEntered(evt);
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                txtStatusTextMouseExited(evt);
            }
        });
        txtStatusText.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtStatusTextActionPerformed(evt);
            }
        });
        txtStatusText.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtStatusTextFocusLost(evt);
            }
        });

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel2.setForeground(new java.awt.Color(255, 0, 0));
        jLabel2.setText(mClient.getClientName());

        jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/online.png"))); // NOI18N
        jLabel3.setText("v");

        jMenu1.setText("Messenger");

        menuMagaeIgnored.setText("Manage ignored users");
        menuMagaeIgnored.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuMagaeIgnoredActionPerformed(evt);
            }
        });
        jMenu1.add(menuMagaeIgnored);

        menuLogout.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_D, java.awt.event.InputEvent.CTRL_MASK));
        menuLogout.setText("Logout");
        menuLogout.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuLogoutActionPerformed(evt);
            }
        });
        jMenu1.add(menuLogout);

        menuExit.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.ALT_MASK));
        menuExit.setText("Exit");
        jMenu1.add(menuExit);

        jMenuBar1.add(jMenu1);

        jMenu3.setText("Action");

        menuGroupChat.setText("Group chat");
        menuGroupChat.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuGroupChatActionPerformed(evt);
            }
        });
        jMenu3.add(menuGroupChat);

        jMenuBar1.add(jMenu3);

        jMenu2.setText("Help");

        menuAbout.setText("About");
        menuAbout.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuAboutActionPerformed(evt);
            }
        });
        jMenu2.add(menuAbout);

        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 280, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel2))
                            .addComponent(txtStatusText))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(7, 7, 7)
                        .addComponent(txtStatusText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(5, 5, 5)
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 18, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 475, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void menuGroupChatActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuGroupChatActionPerformed
        // TODO add your handling code here:
        ArrayList<String> a = new ArrayList<>();
        for (int i = 0; i < mContactEntries.size(); i++) {
            a.add(mContactEntries.get(i).getContactName());
        }

        ContactSelectionDialog inviteDialog = null;
        inviteDialog = new ContactSelectionDialog(this, true, mClient, a);
        inviteDialog.showDialog();
    }//GEN-LAST:event_menuGroupChatActionPerformed

    private void txtStatusTextMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtStatusTextMouseClicked
        // TODO add your handling code here:
        txtStatusText.setBackground(Color.WHITE);
        txtStatusText.selectAll();
        txtStatusText.setEditable(true);
    }//GEN-LAST:event_txtStatusTextMouseClicked

    private void txtStatusTextFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtStatusTextFocusLost
        // TODO add your handling code here:
        txtStatusText.setEditable(false);
        txtStatusText.setBackground(getBackground());
    }//GEN-LAST:event_txtStatusTextFocusLost

    private void formMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMousePressed
        // TODO add your handling code here:
        requestFocus();
    }//GEN-LAST:event_formMousePressed

    private void txtStatusTextMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtStatusTextMouseEntered
        // TODO add your handling code here:
        txtStatusText.setBackground(Color.WHITE);
    }//GEN-LAST:event_txtStatusTextMouseEntered

    private void txtStatusTextMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtStatusTextMouseExited
        // TODO add your handling code here:
        if (!txtStatusText.isEditable()) {
            txtStatusText.setBackground(this.getBackground());
        }
    }//GEN-LAST:event_txtStatusTextMouseExited

    private void txtStatusTextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtStatusTextActionPerformed
        // TODO add your handling code here:
        txtStatusText.setEditable(false);
        txtStatusText.setBackground(getBackground());
        String s = txtStatusText.getText();
        if (s.equals("")) {
            s = "Have something to share?";
        }
        String[] strings = s.split(("'"));
        if (strings.length > 1) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < strings.length; i++) {
                sb.append(strings[i] + "\"");
            }
            sb.deleteCharAt(sb.length() - 1);
            s = sb.toString();
        }


        mClient.sendMessageToServer("" + ClientUtils.REQUEST_CHANGE_STATUS + ":" + mClient.getClientName() + ":" + s);
    }//GEN-LAST:event_txtStatusTextActionPerformed

    private void menuMagaeIgnoredActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuMagaeIgnoredActionPerformed
        // TODO add your handling code here:
        ManageIgnoredUsers dialog = new ManageIgnoredUsers(this, true);
        dialog.setVisible(true);
    }//GEN-LAST:event_menuMagaeIgnoredActionPerformed

    private void menuLogoutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuLogoutActionPerformed
        // TODO add your handling code here:
        if (!mGroupConversasionList.isEmpty()) {
            Set<Integer> iGroupIdList = mGroupConversasionList.keySet();
            for (int i : iGroupIdList) {
                mClient.sendMessageToServer(ClientUtils.REQUEST_OUT_GROUP + ":" + i);
            }
        }
        String command = "" + ClientUtils.REQUEST_LOGOUT + ":"
                + mClient.getClientName();

        mClient.sendMessageToServer(command);
        mClient.closeSession();
    }//GEN-LAST:event_menuLogoutActionPerformed

    private void menuAboutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuAboutActionPerformed
        // TODO add your handling code here:
        AboutBox about=new AboutBox(this, true);
        about.setVisible(true);
    }//GEN-LAST:event_menuAboutActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {// GEN-FIRST:event_formWindowClosing
        // TODO add your handling code here:

        if (!mGroupConversasionList.isEmpty()) {
            Set<Integer> iGroupIdList = mGroupConversasionList.keySet();
            for (int i : iGroupIdList) {
                mClient.sendMessageToServer(ClientUtils.REQUEST_OUT_GROUP + ":" + i);
            }
        }

        String command = "" + ClientUtils.REQUEST_LOGOUT + ":"
                + mClient.getClientName();

        mClient.sendMessageToServer(command);
        mClient.closeSession();

    }// GEN-LAST:event_formWindowClosing

    private void listContactsMouseClicked(java.awt.event.MouseEvent evt) {// GEN-FIRST:event_listContactsMouseClicked
        // TODO add your handling code here:
        JList<ContactEntry> list = (JList<ContactEntry>) evt.getSource();
        if (evt.getClickCount() == 2) {
            int index = list.locationToIndex(evt.getPoint());
            ListModel<?> dlm = list.getModel();
            ContactEntry item = (ContactEntry) dlm.getElementAt(index);
            list.ensureIndexIsVisible(index);

            if (!mPrivateConversasionList.containsKey(item.getContactName())) {
                boolean isOnline = false;
                boolean isIgnored = false;
                if (mContactEntries.contains(item)) {
                    if (mContactEntries.get(mContactEntries.indexOf(item)).isOnline()) {
                        isOnline = true;
                    }
                    if (mIgnoredUser.contains(item.getContactName())) {
                        isIgnored = true;
                    }
                }
                PrivateConversasion conversasion = new PrivateConversasion(mClient,
                        item.getContactName(), isOnline, isIgnored);
                mPrivateConversasionList.put(item.getContactName(), conversasion);
                conversasion.setVisible(true);
            } else {
                mPrivateConversasionList.get(item.getContactName()).setVisible(true);
            }
        }
    }// GEN-LAST:event_listContactsMouseClicked
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenu jMenu3;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JRadioButtonMenuItem jRadioButtonMenuItem1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JList listContacts;
    private javax.swing.JMenuItem menuAbout;
    private javax.swing.JMenuItem menuExit;
    private javax.swing.JMenuItem menuGroupChat;
    private javax.swing.JMenuItem menuLogout;
    private javax.swing.JMenuItem menuMagaeIgnored;
    private javax.swing.JTextField txtStatusText;
    // End of variables declaration//GEN-END:variables

    private void processConfirmFileTransfer(String s) {
        String[] temps = s.split(";");
        int value = JOptionPane.showConfirmDialog(this, "Bạn có muốn nhận file '" + temps[3] + "' từ " + temps[1] + " ?");
        System.out.println(value);
        if (value == 0) {
            JFileChooser fc = new JFileChooser("D:\\");
            fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            fc.setMultiSelectionEnabled(false);
            int check = fc.showDialog(this, null);
            if (check == JFileChooser.APPROVE_OPTION) {
                tempPath = fc.getSelectedFile().getPath();
                System.out.println(tempPath);
            }
            String command = "" + ClientUtils.ASK_FILE_TRANSFER_OK + ";" + temps[1] + ";" + temps[2] + ";" + temps[3];
            mClient.sendMessageToServer(command);
        }
    }

    private void processAskFileTransferOk(String s) {
        String[] temps = s.split(";");
        String command = "" + ClientUtils.FILE_TRANSFERING_TOSERVER + ";" + temps[1] + ";" + temps[2] + ";" + temps[3] + ";";
        try {
            File f = new File(temps[3]);
            byte[] temparray = new byte[(int) f.length()];
            command += String.valueOf(f.length());
            mClient.sendMessageToServer(command);
            BufferedInputStream mrd = new BufferedInputStream(new FileInputStream(f));
            mrd.read(temparray, 0, temparray.length);
            mClient.getSocket().getOutputStream().write(temparray);
            mClient.getSocket().getOutputStream().flush();
        } catch (IOException ex) {
            // mClient.sendMessageToServer(ClientUtils.NOT_ACCEPT);
            System.out.println("send file error");
        }
    }

    private void processFileTransferToClient(String s) {
        String[] temps = s.split(";");
        System.out.println("receiving file");
        try {
            byte[] temparray = new byte[Integer.parseInt("6000")];
            FileOutputStream os = new FileOutputStream(new File(tempPath));
            BufferedInputStream is = new BufferedInputStream(mClient.getSocket().getInputStream());
            int read = 0;
            read = is.read(temparray, 0, temparray.length);
            os.write(temparray);
            os.flush();

        } catch (NumberFormatException | IOException e) {
            System.out.println("receive file error");
        }
    }
}
